import os
from typing import List, Dict, Union
import yaml
import sys

'''
全局配置
自动加载配置文件覆盖当前数据
如果配置文件为空则自动保存当前配置到配置文件
'''
class Config:
    def __init__(self):
        self.basepath = os.path.dirname(os.path.dirname(__file__))  # 获取项目根目录../Auto_Simulated_Universe
        if getattr(sys, 'frozen', False):
            self.basepath = '.'
        self.my_wdh_class = 'CabinetWClass' # 操作窗口类
        self.my_wdh = '文档' # 操作窗口名
        self.config_path = os.path.join(self.basepath, "configs") # 配置文件目录
        self.config_files = [] # 配置文件
        self.timezones = ['America', 'Asia', 'Europe', 'Default'] # 时区
        self.timezone = 'Default' # 使用默认时区
        self.origin_key = ['f','m','shift','v','e','w','a','s','d','1','2','3','4'] # 常用键
        self.mapping = self.origin_key # 待使用按键
        self.save()

    # 加载配置文件
    def load_yaml(self):
        # 检查目录
        if os.path.exists(self.config_path):
            # 扫描文件夹
            for parent, dirnames, filenames in os.walk(self.config_path):
                print("加载：", dirnames, parent, filenames)
                if len(filenames) == 0:
                    self.save_base() # 写出基础配置
                else:
                    self.config_files = filenames # 记录所有配置文件
                    # 扫描所有文件
                    for filename in filenames:
                        with open(os.path.join(self.basepath, filename), "r", encoding="utf-8", errors='ignore') as f:
                            config = yaml.safe_load(f)
                            try:
                                self[filename] = config # 载入所有配置并挂载到对应的配置名下
                            except:
                                pass
        else:
            self.save_base() # 目录不存在直接新建

    # 创建基础文件
    def save_base(self):
        # 直接创建
        with open(os.path.join(self.config_path, "base.yml"), "w", encoding="utf-8") as f:
            yaml.safe_dump({
                "update": {
                    "version_url": "",
                    "download_url": "https://ghproxy.com/https://github.com/CHNZYX/Auto_Simulated_Universe/releases/download/{info['tag_name']}/Auto_Simulated_Universe_{info['tag_name']}.zip",
                    "download_name": "./archive.zip"
                }
            }, f, allow_unicode=True, sort_keys=False)

    # 保存最新配置
    def save(self):
        for filename in self.config_files:
            with open(os.path.join(self.config_path, filename), "w", encoding="utf-8") as f:
                    yaml.safe_dump(self[filename], f, allow_unicode=True, sort_keys=False)

config = Config()